package com.lohika  
{
	import com.lohika.util.GameUtil;
	
	import events.*;
	
	import flash.display.*;
	import flash.text.*;
	
	
	/**
	 * Game Conroller
	 * 
	 * @author Vitaly Vrublevskyy
	 */
	
	public class Game implements IGame 
	{
		private var _container:Sprite;
		
		private var grid:Grid;   //model
		private var board:Board; //view
		
		private var _score:uint;
		private var isPaused:Boolean;
		private var scoreLabel:TextField;
		
		public function Game() 
		{
			_container = new Sprite();
			
			grid = new Grid();
			grid.addEventListener(EntityEvent.ADDED, onEntityAdded);
			grid.addEventListener(EntityEvent.REMOVED, onEntityRemoved);
			grid.addEventListener(GameEvent.UPDATE_SCRORE, onUpdateScore);
			grid.addEventListener(GameEvent.GAME_OVER, onGameOver);
			
			board = new Board(grid); 
			_container.addChild(board);
			
			//addHintLabels();
		}

		
		/* INTERFACE IGame */
		
		public function start():void 
		{
			_score = 0;
			isPaused = false;
			
			grid.initialize();
			board.initialize();
		}

		
		public function pause():Boolean 
		{
			isPaused = !isPaused;
			
			(isPaused) ? 
				board.hide() : 
				board.show();
			
			return isPaused;
		}
		
		public function end():void 
		{
			_container.removeChild(board);
			board = null;
			grid = null;
		}
		
		public function get score():uint  {	
			return _score;	
		}
		
		
		public function get container():Sprite 	{ 
			return _container; 
		}

		/** Listeners */
		
		protected function onUpdateScore(event:GameEvent):void
		{
			_score += event.score;
			//scoreLabel.text = "SCORE: "+ _score;
			GameUtil.playSound(new SoundUpdateScore());
		}
		
		protected function onGameOver(event:GameEvent):void
		{
			event.stopPropagation();
			
			GameUtil.playSound( new SoundGameOver() );
			board.mute();
			
			//redispatch
			event.score = score;
			container.dispatchEvent( event.clone() );
		}		
		
		protected function onEntityRemoved(event:EntityEvent):void
		{
			event.stopPropagation();
			
			var entity:Entity = event.first;
			board.remove(entity);
		}
		
		protected function onEntityAdded(event:EntityEvent):void
		{
			event.stopPropagation();
			
			var entity:Entity = event.first;
			board.add(entity);
			
		}
		
		private function addHintLabels():void
		{
			scoreLabel = new TextField();
			scoreLabel.defaultTextFormat  = GameUtil.getDefaultFontFormat(30);
			scoreLabel.width = 150;
			scoreLabel.x = board.x - scoreLabel.width;
			scoreLabel.y = board.y;
			scoreLabel.text = "SCORE: 0";
			_container.addChild(scoreLabel);
			
			var hint:TextField = new TextField();
			hint.defaultTextFormat = GameUtil.getDefaultFontFormat();
			hint.text  = 'Press "P" for Pause\nPress "Esc" for Game Over'
			hint.width = 300;	
			_container.addChild(hint);
		}
	}

}